package com.docjohnson.pamphlet.fragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.docjohnson.pamphlet.R;
import com.docjohnson.pamphlet.utils.JsonConstants;
import com.docjohnson.pamphlet.utils.LruCache;
import com.docjohnson.pamphlet.utils.Utils;

public class FavouriteItemDetailsFragment extends Fragment implements
		JsonConstants, OnClickListener {

	private JSONObject favItem;
	
	private String pamphletId;
	
	private JSONArray thumbnailList;
	
	private WebView featuresContent;
	private WebView detailesContent;
	
	private static float THUMBNAIL_HEIGHT;
	
	private static final LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(13 * 1024 * 1024) {
		
		@Override
		protected int sizeOf(String key, Bitmap value) {
			return value.getByteCount();
		}
		
		@Override
		public void entryRemoved(String key, Bitmap value) {
			value.recycle();
		}
		
		@Override
		public Bitmap create(String key) {
			Bitmap big = BitmapFactory.decodeFile(key);
			
			Bitmap small = Bitmap.createScaledBitmap(big, (int) (big.getWidth() * THUMBNAIL_HEIGHT / big.getHeight()), (int) (THUMBNAIL_HEIGHT), true);
			
			big.recycle();
			
			return small;
		}
	};
	
	public static FavouriteItemDetailsFragment create(String pamphletId, JSONObject favItem) {
		return new FavouriteItemDetailsFragment(pamphletId, favItem);
	}
	
	private FavouriteItemDetailsFragment() {
		
	}
	
	private FavouriteItemDetailsFragment(String pamphletId, JSONObject favItem) {
		this.favItem = favItem;
		this.pamphletId = pamphletId;
	}
	
//	private WeakReference<Bitmap> bigImageBitmap = null;
	private Bitmap bigImageBitmap = null;
	
	public void setFavouritItemJson(JSONObject favItem) {
		View root = getView();
		if (favItem != null) {
			((TextView) root.findViewById(R.id.title)).setText(favItem
					.optString(NAME, ""));
			((TextView) root.findViewById(R.id.description)).setText(favItem
					.optString(DESCRIPTION, ""));

			bigImageBitmap = BitmapFactory.decodeFile(Utils.mapServerFileToLocal(pamphletId, favItem.optString(IMAGE, "")));
			
			BitmapDrawable image = new BitmapDrawable(getResources(), bigImageBitmap);

			((ImageView) root.findViewById(R.id.image)).setImageDrawable(image);

			Gallery thumbnailGallery = (Gallery) root.findViewById(R.id.thumbnails);
			try {
				thumbnailGallery.setAdapter(new ThumbnailAdapter(thumbnailList = favItem
						.getJSONArray(THUMBNAIL)));
				thumbnailGallery.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						if (bigImageBitmap != null) {
							bigImageBitmap.recycle();
						}
						
						try {
							bigImageBitmap = BitmapFactory.decodeFile(Utils.mapServerFileToLocal(pamphletId, thumbnailList.getString(position)));
							BitmapDrawable image = new BitmapDrawable(getResources(), bigImageBitmap);
							
							((ImageView) getView().findViewById(R.id.image)).setImageDrawable(image);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		
		root.findViewById(R.id.btn_close).setOnClickListener(this);
		
		featuresContent = (WebView) root.findViewById(R.id.features_content);
		detailesContent = (WebView) root.findViewById(R.id.detailes_content);
		
		featuresContent.loadData(favItem.optString(JsonConstants.FEATURES), "text/html", null);
		detailesContent.loadData(favItem.optString(JsonConstants.DETAILS), "text/html", null);
		
		root.findViewById(R.id.btn_detailes).setOnClickListener(this);
		root.findViewById(R.id.btn_features).setOnClickListener(this);
		
		featuresContent.setVisibility(View.VISIBLE);
		detailesContent.setVisibility(View.GONE);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
		THUMBNAIL_HEIGHT =Utils.dipToPixel(64, getResources());
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.favourite_item, null);
		return root;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		setFavouritItemJson(favItem);
	}
	
	private class ThumbnailAdapter extends BaseAdapter {

		private JSONArray thumbnailList;
		
		

		public ThumbnailAdapter(JSONArray thumbnailList) {
			this.thumbnailList = thumbnailList;
		}

		@Override
		public int getCount() {
			return thumbnailList.length();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = new ImageView(getActivity());
				ImageView image = (ImageView) convertView;
				image.setLayoutParams(new Gallery.LayoutParams((int) Utils
						.dipToPixel(64, getResources()), (int) Utils
						.dipToPixel(64, getResources())));
				image.setScaleType(ScaleType.FIT_CENTER);
				try {
					image.setImageDrawable(new BitmapDrawable(getResources(), bitmapCache.get(
						Utils.mapServerFileToLocal(pamphletId, thumbnailList
								.getString(position)))));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return convertView;
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_detailes:
			featuresContent.setVisibility(View.GONE);
			detailesContent.setVisibility(View.VISIBLE);
			break;
			
		case R.id.btn_features:
			detailesContent.setVisibility(View.GONE);
			featuresContent.setVisibility(View.VISIBLE);
			break;
			
		case R.id.btn_close:
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
			transaction.setCustomAnimations(R.animator.fade_enter, R.animator.fade_exit);
			transaction.remove(this);
			transaction.commit();
			break;
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
}
